<template>
  <div class="upload">
    <van-uploader
      ref="fileListRef"
      v-model="fileList"
      :before-read="beforeRead"
      :after-read="afterRead"
      :preview-full-image="false"
      :max-count="1"
      :deletable="false"
    >
      <img v-show="imgSrc" :src="imgSrc" class="avatarImg" alt="">
      <img v-show="!imgSrc" :src="require('./images/avatar.png')" class="avatarImg" alt="">
    </van-uploader>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { Toast } from 'vant'
import { uploadUserHeadImg } from './../../api/user'

export default {
  name: 'Uploader',
  data() {
    return {
      fileList: [],
      imgSrc: ''
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  created() {
    this.$nextTick(() => {
      this.imgSrc = this.userInfo.userPicture
    })
  },
  methods: {
    ...mapActions('user', ['updateAvatar']),

    beforeRead(file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        Toast('请上传 jpg 或 png 格式图片')
        return false
      }

      if (!isLt2M) {
        Toast('上传头像图片大小不能超过 2MB!')
        return false
      }

      const url = window.URL || window.webkitURL || window.mozURL
      const src = url.createObjectURL(file) // 本地临时的地址
      this.imgSrc = src

      return isImg && isLt2M
    },

    async afterRead(file) {
      const params = new FormData()
      params.append('muFile', file.file)
      Toast.loading({
        duration: 20000,
        message: '加载中...',
        forbidClick: true
      })
      const { code, data, msg } = await uploadUserHeadImg(params)

      if (code === 0) {
        this.imgSrc = data
        Toast.clear()
        this.updateAvatar(data).then(() => {
          Toast.success(msg)
        }).catch(error => {
          console.log(error)
        })
      } else {
        this.imgSrc = ''
        Toast.fail(msg)
      }

      this.$nextTick(() => {
        this.$refs.fileListRef.deleteFile(file, 0)
      })
    }
  }
}
</script>

<style scoped lang="less">
.upload {
  .avatarImg {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
}
</style>
